package tech.wetech.admin.modules.system.timing;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import tech.wetech.admin.modules.system.mapper.PayCompanyInfoMapper;
import tech.wetech.admin.modules.system.po.PayCompanyInfo;
import tech.wetech.admin.modules.system.service.impl.CCBPayServiceImpl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Configuration
@EnableScheduling   // 开启定时任务
@Slf4j
public class TimingUpdateSecretKeyTask {

  @Autowired
  private CCBPayServiceImpl ccbPayService;

  @Autowired
  private PayCompanyInfoMapper payCompanyInfoMapper;

  // 每天凌晨一点执行 0 0 1 * * ? 每五秒执行一次0/5 * * * * ?
  @Scheduled(cron = "0 0 1 * * ?")
  private void configureTasks() throws InterruptedException {
    System.err.println("执行静态定时任务时间: " + LocalDateTime.now());
    // 获取上月今天时间
    LocalDate today = LocalDate.now();
    LocalDate lastMonthToday = today.minusMonths(1);

    Map<String, String> newRemark = new HashMap<>();
    newRemark.put("ccb_last_update", today.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));

    List<PayCompanyInfo> payCompanyInfos = payCompanyInfoMapper.list();

    for (PayCompanyInfo payCompanyInfo : payCompanyInfos) {
      if (StringUtils.isBlank(payCompanyInfo.getPayJson())) {
        continue;
      }

      try {

        Map<String, Object> map = JSON.parseObject(payCompanyInfo.getPayJson(), Map.class);
        // 为空执行下次
        if (!map.containsKey("scan_key")) {
          continue;
        }
        if (Objects.isNull(map.get("scan_key"))) {
          continue;
        }
        // 判断Scan_key不为空更新密钥

        if (StringUtils.isEmpty(payCompanyInfo.getRemark())) {
          Map<String, String> map1 = ccbPayService.updateSecretKey(payCompanyInfo.getCompanyId());
          // 刷新下次更新时间
          payCompanyInfoMapper.updateRemarkByCompanyId(payCompanyInfo.getId(),
              payCompanyInfo.getCompanyId(), JSON.toJSONString(newRemark));
          log.info("newKey:{}", map1.get("key"));
          continue;
        }

        Map<String, String> dbRemark = JSON.parseObject(payCompanyInfo.getRemark(), Map.class);
        LocalDate lastUpdate = LocalDate.parse(dbRemark.get("ccb_last_update"), DateTimeFormatter.ofPattern("yyyy-MM-dd"));

        if (lastUpdate.isBefore(lastMonthToday)) {
          Map<String, String> map2 = ccbPayService.updateSecretKey(payCompanyInfo.getCompanyId());
          // 刷新下次更新时间
          boolean update = payCompanyInfoMapper.updateRemarkByCompanyId(payCompanyInfo.getId(), payCompanyInfo.getCompanyId(), JSON.toJSONString(newRemark));
          log.info("newKey:{}", map2.get("key"));
          if (!update) {
            throw new RuntimeException("更新时间失败");
          }
        }
      } catch (Exception e) {
        log.info("更新密钥失败", e);
      }
    }
  }
}
